package com.manager.plat.dao.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.manager.plat.dao.IFilterDao;
import com.manager.plat.util.BaseUtil;
import com.manager.plat.vo.FilterVo;

public class FilterDaoImpl extends JdbcDaoSupport implements IFilterDao {
	private static Logger logger = Logger.getLogger(FilterDaoImpl.class);
	
	/**获得所有渠道扣量配置信息列表*/
	@SuppressWarnings("unchecked")
	@Override
	public List<FilterVo> getFilterList() {
		String sql = "select f.id, f.lower_id, pl.name lower_name, f.sp_number, f.province, f.num, f.start_time, f.end_time " +
				 "from tb_ivr_filter f " +
				 "inner join tb_ivr_partner_lower pl on pl.id = f.lower_id and pl.status = 1 " +
				 "where f.status = 1";
		logger.info(String.format("获得所有渠道扣量配置信息列表[%s]", sql));
		List<FilterVo> configFilterVoList = this.getJdbcTemplate().query(sql, rowMapper);
		if(configFilterVoList != null && configFilterVoList.size() > 0){
			return configFilterVoList;
		}
		return null;
	}
	/**数据转换*/
	private ParameterizedRowMapper<FilterVo> rowMapper = new ParameterizedRowMapper<FilterVo>() {
		@Override
		public FilterVo mapRow(ResultSet rs, int rowNum) throws SQLException {
			FilterVo filterVo = new FilterVo();
			filterVo.setId(rs.getInt("id"));
			filterVo.setLower_id(rs.getInt("lower_id"));
			filterVo.setLower_name(rs.getString("lower_name"));
			filterVo.setSp_number(rs.getString("sp_number"));
			filterVo.setProvince(rs.getString("province"));
			filterVo.setNum(rs.getInt("num"));
			filterVo.setStart_time(rs.getString("start_time"));
			filterVo.setEnd_time(rs.getString("end_time"));
			return filterVo;
		}
	};
	/**批量保存渠道扣量配置信息*/
	@Override
	public int batchInsertFilter(List<FilterVo> filterList) {
		String sql = "insert into tb_ivr_filter(lower_id, sp_number, province, num, start_time, end_time, status) values(?,?,?,?,?,?,1)";
		
		int[] count = this.getJdbcTemplate().batchUpdate(sql, new autoInsertFilterPsSetter(filterList));
		if(count.length > 0){
			return count.length;
		}
		return 0;
	}
	
	private class autoInsertFilterPsSetter implements BatchPreparedStatementSetter{
		final List<FilterVo> filterListTemp;
		public autoInsertFilterPsSetter(List<FilterVo> filterList){
			filterListTemp = filterList;
		}
		
		@Override
		public void setValues(PreparedStatement ps, int i) throws SQLException {
			FilterVo filterVo = filterListTemp.get(i);
			ps.setInt(1, filterVo.getLower_id());
			ps.setString(2, filterVo.getSp_number());
			ps.setString(3, filterVo.getProvince());
			ps.setInt(4, filterVo.getNum());
			ps.setString(5, filterVo.getStart_time());
			ps.setString(6, filterVo.getEnd_time());
		}
		@Override
		public int getBatchSize() {
			return filterListTemp.size();
		}
	}
	/**修改渠道扣量信息*/
	@Override
	public int updateLowerFilter(FilterVo filterVo) {
		String sql = "update tb_ivr_filter set num = ?, start_time = ?, end_time = ?, thres_hold = ? where lower_id = ? and province = ?";
		Object[] param = new Object[]{filterVo.getNum(), filterVo.getStart_time(), filterVo.getEnd_time(), createThres_hold(filterVo), filterVo.getLower_id(), filterVo.getProvince()};
		logger.info(String.format("修改渠道扣量信息[%s]", BaseUtil.logSQL(sql, param)));
		
		int count = this.getJdbcTemplate().update(sql, param);
		return count;
	}
	/**根据Id获得渠道扣量配置信息*/
	@SuppressWarnings("unchecked")
	@Override
	public FilterVo getFilterById(int id) {
		String sql = "select id, lower_id, sp_number, province, num, start_time, end_time from tb_ivr_filter where id = ? and status = 1";
		Object[] param = new Object[]{id};
		logger.info(String.format("根据Id获得渠道扣量配置信息[%s]", BaseUtil.logSQL(sql, param)));
		
		List<FilterVo> filterVoList = this.getJdbcTemplate().query(sql, param, tempMapper);
		if(filterVoList != null && filterVoList.size() > 0){
			return filterVoList.get(0);
		}
		return null;
	}
	/**数据转换*/
	private ParameterizedRowMapper<FilterVo> tempMapper = new ParameterizedRowMapper<FilterVo>() {
		@Override
		public FilterVo mapRow(ResultSet rs, int rowNum) throws SQLException {
			FilterVo filterVo = new FilterVo();
			filterVo.setId(rs.getInt("id"));
			filterVo.setLower_id(rs.getInt("lower_id"));
			filterVo.setSp_number(rs.getString("sp_number"));
			filterVo.setProvince(rs.getString("province"));
			filterVo.setNum(rs.getInt("num"));
			filterVo.setStart_time(rs.getString("start_time"));
			filterVo.setEnd_time(rs.getString("end_time"));
			return filterVo;
		}
	};
	/**修改长号码扣量信息*/
	@Override
	public int updateFilter(FilterVo filterVo) {
		String sql = "update tb_ivr_filter set num = ?, start_time = ?, end_time = ?, thres_hold = ? where id = ?";
		Object[] param = new Object[]{filterVo.getNum(),filterVo.getStart_time(),
									filterVo.getEnd_time(), createThres_hold(filterVo), filterVo.getId()};
		logger.info(String.format("修改长号码扣量信息[%s]", BaseUtil.logSQL(sql, param)));
		
		int count = this.getJdbcTemplate().update(sql, param);
		return count;
	}
	
	/**删除长号码扣量信息*/
	@Override
	public int deleteFilter(int id) {
		String sql = "delete from tb_ivr_filter where id = ?";
		Object[] param = new Object[]{id};
		logger.info(String.format("删除长号码扣量信息[%s]", BaseUtil.logSQL(sql, param)));

		int count = this.getJdbcTemplate().update(sql, param);
		return count;
	}
	/**删除渠道扣量信息*/
	@Override
	public int deleteLowerFilter(int lower_id, String province) {
		String sql = "delete tb_ivr_filter where lower_id = ? and province = ?";
		Object[] param = new Object[]{lower_id, province};
		logger.info(String.format("删除渠道扣量信息[%s]", BaseUtil.logSQL(sql, param)));

		int count = this.getJdbcTemplate().update(sql, param);
		return count;
	}
	
	/** 随机产生扣量数组 */
	private String createThres_hold(FilterVo configFilterVo) {
		
		String thres_hold = "";
		if(configFilterVo.getNum() == 0)
			return null;
		
		for(int i = 0; i < configFilterVo.getNum() ; i++) {
			int random = (int) (1+Math.random() * 100);
			logger.info(String.format("长号码[%s],随机数量[%d]，产生随机数序列号为[%d]", configFilterVo.getSp_number(), configFilterVo.getNum(), random));
			if (i == 0) {
				thres_hold = String.valueOf(random);
			}
			else {
				thres_hold += "," + String.valueOf(random);
			}
		}
		
		return thres_hold;
	}
}
